package com.edou.system.service.impl;

import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.edou.base.util.UUIDUtil;
import com.edou.system.dto.OSSFileAuthType;
import com.edou.system.service.IAliyunOSSService;

@Service("aliyunOSSServiceImpl")
@Transactional
public class AliyunOSSServiceImpl implements IAliyunOSSService{
	
	private Log logger = LogFactory.getLog(AliyunOSSServiceImpl.class);
	
	@Value("${aliyun.oss.endpoint:{NULL}}")
	private String endpoint;
	@Value("${aliyun.oss.accesskeyid:{NULL}}")
	private String accessKeyId;
	@Value("${aliyun.oss.accesskeysecret:{NULL}}")
	private String accessKeySecret;
	@Value("${aliyun.oss.bucketname.publicforread:{NULL}}")
	private String bucketNameForPublicRead;
	@Value("${aliyun.oss.bucketname.private:{NULL}}")
	private String bucketNameForPrivate;
	
	public AliyunOSSServiceImpl() {
		super();
		
	}
	
	/**
	 * 上传公开文件
	 * @param uploadFile 待上传的文件
	 * @param ossFileAuthType 文件权限
	 * @return 返回上传后的文件名
	 */
	public String uploadFile(File uploadFile,OSSFileAuthType ossFileAuthType){
		String fileKey = null;
		OSSClient ossClient = null;
		try{
			ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
			//获取文件后缀
			int point = uploadFile.getName().lastIndexOf(".");
			String fileExt = uploadFile.getName().substring(point);
			fileKey = UUIDUtil.uuid() + fileExt;
			//上传
			if(ossFileAuthType == OSSFileAuthType.pub){
				ossClient.putObject(bucketNameForPublicRead, fileKey, uploadFile);
			}else{
				ossClient.putObject(bucketNameForPrivate, fileKey, uploadFile);
			}
		}catch(Exception ex){
			String msg = "阿里云OSS组件上传公开文件发生异常：" + ex.getMessage();
			logger.error(msg,ex);
		}finally{
			if(null != ossClient){
				ossClient.shutdown();
			}
		}
		
		return fileKey;
	}

	/**
	 * 下载文件
	 * @param ossFileKey OSS文件key
	 * @param localFile 本地文件
	 */
	public void downloadFile(String ossFileKey,File localFile,OSSFileAuthType ossFileAuthType){
		OSSClient ossClient = null;
		try{
			ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
			//下载
			if(ossFileAuthType == OSSFileAuthType.pub){
				ossClient.getObject(new GetObjectRequest(bucketNameForPublicRead, ossFileKey), localFile);
			}else{
				ossClient.getObject(new GetObjectRequest(bucketNameForPrivate, ossFileKey), localFile);
			}
		}catch(Exception ex){
			String msg = "阿里云OSS组件下载私有文件发生异常：" + ex.getMessage();
			logger.error(msg,ex);
		}finally{
			if(null != ossClient){
				ossClient.shutdown();
			}
		}
		
	}
}
